package com.offcn.com.stack;

import java.util.Scanner;
import java.util.Stack;

/*
计算逆波兰式（后缀表达式）的值
运算符仅包含"+","-","*"和"/"，被操作数可能是整数或其他表达式
 */
public class Exercise {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入字符数字包含加减乘除符合的字符串：");
        String[] strArr = {"100","20","/","10","+","30","*"};

        int calculator = getCalculator(strArr);
        System.out.println("calculator = " + calculator);
    }

    private static int  getCalculator(String[] strArr) {

        Stack<Integer> stack = new Stack<>();
        int sum;
        int op1 = 0;
        int op2 = 0;
        for (int i = 0; i <strArr.length ; i++) {
            switch (strArr[i]) {
                case "+":
                    op1= stack.pop();
                    op2 = stack.pop();
                    stack.push(op1 + op2);
                    break;
                case "-":
                    op1= stack.pop();
                    op2 = stack.pop();
                    stack.push(op1 - op2);
                    break;
                case "*":
                    op1= stack.pop();
                    op2 = stack.pop();
                    stack.push(op1 * op2);
                    break;
                case "/":
                    op1= stack.pop();
                    op2 = stack.pop();
                    stack.push(op1 / op2);
                    break;
                default:
                    stack.push(Integer.parseInt(strArr[i]));
            }
        }
        return stack.peek();
    }


}
